package main

import (
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
	"log"
	"net/http"
	"net/url"
	"strconv"
)

// 菜单
type Meal struct {
	Id    int
	Title string
	Price int
	Site  int `1`
}

type Meals []Meal

var sites []string = []string{"", "dian1", "dian2"}

type MenuController struct {
	Controller
}

func (m *MenuController) Init(rw http.ResponseWriter, form url.Values) {
	m.Rw = rw
	m.Form = form
	m.Tpl = "menu.tpl"
	log.Println("加载 menu ...")
}

func (m *MenuController) Get() {
	site, _ := strconv.Atoi(m.Form.Get("s"))
	if site == 0 {
		site = 1
	}
	var ms Meals
	ms = getall(site)
	data := make(map[string]interface{}, 2)
	data["title"] = "菜单！"
	data["site"] = site
	data["sitename"] = sites[site]
	data["ms"] = ms
	log.Printf("%T, %v", data, data)

	m.Display(data)
	// for _, m := range ms {
	// 	log.Fprintf(rw, m.Title)
	// }
}

func (m *MenuController) Post() {

	site, _ := strconv.Atoi(m.Form.Get("s"))
	if site == 0 {
		site = 1
	}

	meal := make(map[string]string)
	meal["title"] = m.Form.Get("title")
	meal["price"] = m.Form.Get("price")
	meal["site"] = m.Form.Get("site")

	db, err := sql.Open("sqlite3", DbName)
	checkErr(err)
	defer db.Close()

	stmt, err := db.Prepare("insert into menu (title,price,site) values (?,?,?)")
	checkErr(err)
	defer stmt.Close()
	res, err := stmt.Exec(meal["title"], meal["price"], meal["site"])
	checkErr(err)
	if id, _ := res.LastInsertId(); id > 0 {
		m.Get()
	}

}

func getall(site int) (ms Meals) {
	db, err := sql.Open("sqlite3", DbName)
	checkErr(err)
	defer db.Close()

	stmt, err := db.Prepare("select * from menu where site=?")
	checkErr(err)
	defer stmt.Close()
	rows, err := stmt.Query(site)
	defer rows.Close()

	for rows.Next() {
		m := Meal{}
		err = rows.Scan(&m.Id, &m.Title, &m.Price, &m.Site)
		checkErr(err)
		ms = append(ms, m)
	}

	return
}
